<?php
/**
 * Created by andrei
 * Date: 10/25/12
 * Time: 9:37 AM
 */
class Page_Fe_Products_MemoryList extends Page {
	/**
	 * @var Db_Products_Products
	 */
	protected $tableObject;
	protected static $memoryListProducts = null;

	function __construct() {
		self::$TPL->appendCssFile('wedding/memory_list');
		self::$TPL->appendJsFile('wedding/memory_list');
        self::$TPL->appendJsFile('wedding/popup_preview');
		self::$TPL->setBodyClass('memory_list_page');
		Config::set('USE_MEMORY_LIST', false);
		parent::__construct();
	}

	public function defaultAction() {
		self::$TPL->setBodyTemplate('memory_list');

		$memoryListObj = new Db_Products_MemoryList();
		$memoryListProductsObj = new Db_Products_MemoryListProducts();
		//$memoryListObj->addProductToMemoryList(811, 'ra5mg15mbt', 61);
		$memoryListProducts = $memoryListProductsObj->getAllProductsByMemoryIdentifier(cookie(MEMORY_LIST_NAME_KEY));
		self::$TPL->assign('memoryListProducts', $memoryListProducts);

		$productsUrls = Db_Cms_PagePagination::getProductsUrlsByPageId(self::$PROJECT['pr_identifier'], 0, false);
		self::$TPL->assign('productsUrls', $productsUrls);

		$productsCategories = Db_Products_Products::getProductsCategories();
		self::$TPL->assign('productsCategories', $productsCategories);

		$cart = self::$S->Get('cart');
		self::$TPL->assign('cart', $cart);

		return array(
			'type' => 'display',
		);
	}

	public function ajaxAddToWishlistAction() {
		$encodedProductId = post('productId', 'string');
		$memoryIdentifier = post('memoryListId', 'string');
		$themeId = post('themeId', 'int');
		$productId = Utils::memoryProductIdDecode($encodedProductId);
		$result = false;
		if ($productId && $memoryIdentifier && $themeId) {
			$memoryList = new Db_Products_MemoryList();
			$result = $memoryList->addProductToMemoryList($productId, $memoryIdentifier, $themeId);
		}
		return array(
			'type' => 'encoded_json',
			'content' => json_encode($result)
		);
	}

	public function ajaxSaveMemoryNameAction() {
		$memoryName = post('memoryName', 'str');
		$currentMemoryId = post('currentMemoryId', 'str');
		$memoryProductId = Utils::memoryProductIdDecode($currentMemoryId);

		$memoryListProductsObj = new Db_Products_MemoryListProducts($memoryProductId);
		if (!$memoryListProductsObj->id) {
			return array(
				'type' => 'json',
				'content'=> '0'
			);
		}
		$memoryListProductsObj->mlp_name = $memoryName;
		if ($memoryListProductsObj->save()) {
			return array(
				'type' => 'json',
				'content'=> 1
			);
		} else {
			return array(
				'type' => 'json',
				'content'=> 0
			);
		}

	}

	public function ajaxDeleteMemoryProductAction() {
		$memoryIdEncoded = post('memoryId', 'str');
		$memoryProductId = Utils::memoryProductIdDecode($memoryIdEncoded);
		$memoryListProductsObj = new Db_Products_MemoryListProducts();
		if ($memoryListProductsObj->abstractDelete($memoryProductId)) {
			Db_Products_MemoryListProductPages::abstractDeleteByField('mpp_memory_product_id', $memoryProductId);
			Db_Products_MemoryListProductPageTexts::abstractDeleteByField('mppt_memory_product_page_id', $memoryProductId);
			Db_Products_MemoryListProductPageImages::abstractDeleteByField('mppi_memory_product_page_id', $memoryProductId);
			return array(
				'type' => 'json',
				'content'=> 1
			);
		} else {
			return array(
				'type' => 'json',
				'content'=> 0
			);
		}
	}

	public function ajaxDuplicateMemoryProductAction() {
		$memoryIdEncoded = post('memoryId', 'str');
		$memoryProductId = Utils::memoryProductIdDecode($memoryIdEncoded);

		$memoryListProductsObj = new Db_Products_MemoryListProducts($memoryProductId);

		$memoryListProductsObj->id = null;
		$memoryListProductsObj->mlp_memory_id = $memoryListProductsObj->objectArray->mlp_memory_id;
		$memoryListProductsObj->mlp_product_id = $memoryListProductsObj->objectArray->mlp_product_id;
		$memoryListProductsObj->mlp_theme_id = $memoryListProductsObj->objectArray->mlp_theme_id;

		$getVersion = $memoryListProductsObj->findByFields(array('mlp_memory_id' => $memoryListProductsObj->objectArray->mlp_memory_id,'mlp_product_id' => $memoryListProductsObj->objectArray->mlp_product_id), 'AND', 'id DESC');
		$version = (isset($getVersion) ? intval($getVersion->mlp_version) + 1 : null );
		$timeNow = time();
		$mlpName = 'Version '.$version .' ' . date('H:i',$timeNow). ' | ' .  Utils::formatDateUser($timeNow,false);

		$memoryListProductsObj->mlp_version = $version;
		$memoryListProductsObj->mlp_name = $mlpName;
		$memoryListProductsObj->mlp_edited_by_user = $memoryListProductsObj->objectArray->mlp_edited_by_user;
		$memoryListProductsObj->mlp_date = Utils::formatDateDb($timeNow, true);
		$memoryListProductsObj->mlp_ordered = $memoryListProductsObj->objectArray->mlp_ordered;

		if ($memoryListProductsObj->save()) {

			//duplicate memory_list_product_pages
			$memoryListProductPagesObj = new Db_Products_MemoryListProductPages();
			$memoryListProductPageTextsObj = new Db_Products_MemoryListProductPageTexts();
			$memoryListProductPageImagesObj = new Db_Products_MemoryListProductPageImages();

			$memoryListProductPages = $memoryListProductPagesObj->findAllByField('mpp_memory_product_id', $memoryProductId);
			if ($memoryListProductPages) {
				foreach ($memoryListProductPages as $memoryProductPage) {
					$memoryListProductPagesObj->id = null;
					$memoryListProductPagesObj->mpp_memory_product_id = $memoryListProductsObj->id;
					$memoryListProductPagesObj->mpp_template_id = $memoryProductPage->mpp_template_id;
					$memoryListProductPagesObj->mpp_page_index = $memoryProductPage->mpp_page_index;
					if ($memoryListProductPagesObj->save()) {
						$memoryListProductPageTexts = $memoryListProductPageTextsObj->findAllByField('mppt_memory_product_page_id', $memoryProductPage->id);
						if ($memoryListProductPageTexts) {
							foreach ($memoryListProductPageTexts as $memoryProductPageText) {
								$memoryListProductPageTextsObj->id = null;
								$memoryListProductPageTextsObj->mppt_memory_product_page_id = $memoryListProductPagesObj->id;
								$memoryListProductPageTextsObj->mppt_layout_item_id = $memoryProductPageText->mppt_layout_item_id;
								$memoryListProductPageTextsObj->mppt_text = $memoryProductPageText->mppt_text;
								$memoryListProductPageTextsObj->mppt_font_family = $memoryProductPageText->mppt_font_family;
								$memoryListProductPageTextsObj->mppt_font_size = $memoryProductPageText->mppt_font_size;
								$memoryListProductPageTextsObj->mppt_text_align = $memoryProductPageText->mppt_text_align;
								$memoryListProductPageTextsObj->mppt_vertical_align = $memoryProductPageText->mppt_vertical_align;
								$memoryListProductPageTextsObj->mppt_color = $memoryProductPageText->mppt_color;
								$memoryListProductPageTextsObj->mppt_rotation = $memoryProductPageText->mppt_rotation;
								$memoryListProductPageTextsObj->mppt_width = $memoryProductPageText->mppt_width;
								$memoryListProductPageTextsObj->mppt_height = $memoryProductPageText->mppt_height;
								$memoryListProductPageTextsObj->mppt_x = $memoryProductPageText->mppt_x;
								$memoryListProductPageTextsObj->mppt_y = $memoryProductPageText->mppt_y;
								$memoryListProductPageTextsObj->mppt_line_height = $memoryProductPageText->mppt_line_height;
								$memoryListProductPageTextsObj->save();
							}
						}
						$memoryListProductPageImages = $memoryListProductPageImagesObj->findAllByField('mppi_memory_product_page_id', $memoryProductPage->id);
						if ($memoryListProductPageImages) {
							foreach ($memoryListProductPageImages as $memoryProductPageImage) {
								$memoryListProductPageImagesObj->id = null;
								$memoryListProductPageImagesObj->mppi_memory_product_page_id = $memoryListProductPagesObj->id;
								$memoryListProductPageImagesObj->mppi_layout_item_id = $memoryProductPageImage->mppi_layout_item_id;
								$memoryListProductPageImagesObj->mppi_photo_id = $memoryProductPageImage->mppi_photo_id;
								$memoryListProductPageImagesObj->mppi_iw = $memoryProductPageImage->mppi_iw;
								$memoryListProductPageImagesObj->mppi_ih = $memoryProductPageImage->mppi_ih;
								$memoryListProductPageImagesObj->mppi_ir = $memoryProductPageImage->mppi_ir;
								$memoryListProductPageImagesObj->mppi_ix = $memoryProductPageImage->mppi_ix;
								$memoryListProductPageImagesObj->mppi_iy = $memoryProductPageImage->mppi_iy;
								$memoryListProductPageImagesObj->mppi_image_filter = $memoryProductPageImage->mppi_image_filter;
								$memoryListProductPageImagesObj->mppi_rotation = $memoryProductPageImage->mppi_rotation;
								$memoryListProductPageImagesObj->mppi_width = $memoryProductPageImage->mppi_width;
								$memoryListProductPageImagesObj->mppi_height = $memoryProductPageImage->mppi_height;
								$memoryListProductPageImagesObj->mppi_x = $memoryProductPageImage->mppi_x;
								$memoryListProductPageImagesObj->mppi_y = $memoryProductPageImage->mppi_y;
								$memoryListProductPageImagesObj->save();
							}
						}

					}
				}
			}


			$dataJson = array(
				'id' => Utils::memoryProductIdEncode($memoryListProductsObj->id),
				'productId' => Utils::memoryProductIdEncode($memoryListProductsObj->objectArray->mlp_product_id),
				'name' => $mlpName,
				'dateNew' => date('H:i d.m.Y', $timeNow)
			);
			return array(
				'type' => 'json',
				'content' => $dataJson
			);
		} else {
			return array(
				'type' => 'json',
				'content' => 0
			);
		}
	}

	public function ajaxSendMlEmailAction() {
		$email = post('email', 'string');
		$memoryListId = post('memoryListId', 'string');
		if (!$email || !$memoryListId) {
			return false;
		}

        $webSite = self::$SETTINGS['website'];
        $memoryListUrl = self::$PROJECT["pr_domain_".conf('ENVIRONMENT')] . conf('MEMORY_LIST_PAGE_URL') . "?mlid=" . $memoryListId;
        $contactPhoneNumber1 = self::$SETTINGS['contact_phone_number1'];
        $contactPhoneNumber2 = self::$SETTINGS['contact_phone_number2'];
        $contactName = self::$SETTINGS['contact_name'];
        $companyWebsite = self::$SETTINGS['company_website'];
        $companyRepresented = self::$SETTINGS['company_represented'];
        $registerCourt = self::$SETTINGS['register_court'];
        $contactEmail = self::$SETTINGS['contact_email'];
        $registrationNumber = self::$SETTINGS['registration_number'];
        $contactAddress = self::$SETTINGS['contact_address'];
        $postCodAddress = self::$SETTINGS['post_cod_address'];

        self::$TPL->assign('webSite', $webSite);
        self::$TPL->assign('memoryListUrl', $memoryListUrl);
        self::$TPL->assign('contactPhoneNumber1', $contactPhoneNumber1);
        self::$TPL->assign('contactPhoneNumber2', $contactPhoneNumber2);
        self::$TPL->assign('contactName', $contactName);
        self::$TPL->assign('contactEmail', $contactEmail);
        self::$TPL->assign('contactAddress', $contactAddress);
        self::$TPL->assign('postCodAddress', $postCodAddress);
        self::$TPL->assign('companyWebsite', $companyWebsite);
        self::$TPL->assign('companyRepresented', $companyRepresented);
        self::$TPL->assign('registerCourt', $registerCourt);
        self::$TPL->assign('registrationNumber', $registrationNumber);
        $emailHtmlContent = self::$TPL->display('memory_list_mail', true);

        $imagesNameToMail = array('sn_facebook', 'sn_google', 'sn_twitter', 'sn_pinterest', 'sn_xing', 'sn_linkedin');
        $pathToMailImg = ROOT_PATH.'public/static/common/pics/';

        $pathHeaderMailImg = ROOT_PATH.'public/static/'.self::$PROJECT['pr_identifier'].'/default/pics/';
        Utils::instantiateMail();

        foreach ($imagesNameToMail AS $imgName) {
            self::$MAIL->AddEmbeddedImage($pathToMailImg.$imgName.'.png', $imgName);
        }
        self::$MAIL->AddEmbeddedImage($pathHeaderMailImg.'email_header.jpg', 'email_header');
        self::$MAIL->Subject = t(T_PROJECT_TITLE, self::$PROJECT["pr_name"]);
        self::$MAIL->AddEmbeddedImage('', '');
		self::$MAIL->Body = $emailHtmlContent;
        self::$MAIL->SetFrom($contactEmail, $webSite);
        self::$MAIL->AddReplyTo($contactEmail, $webSite);
        self::$MAIL->AddAddress($email);
        self::$MAIL->IsHTML(true);
		$response = Utils::$MAIL->Send();
		if ($response == 'true') {
			return array(
				'type' => 'json',
				'content' => true
			);
		} else {
			return array(
				'type' => 'json',
				'content' => false
			);
		}
	}

	public function ajaxRemoveFromBasketAction() {
		$cartArray = self::$S->Get('cart');
		$mlpId = post('mlpId', 'str');
		if (isset($cartArray[$mlpId])) {
			unset($cartArray[$mlpId]);
		}
		self::$S->Set('cart', $cartArray);
		return array(
			'type' => 'json',
			'content' => 1
		);
	}

	public function ajaxDeleteFromWishlistAction(){
		$memoryListProductId = Utils::memoryProductIdDecode(post('memoryListProductId', 'str'));
		$success = false;
		if ($memoryListProductId) {
			$success = Db_Products_MemoryListProducts::abstractDelete($memoryListProductId);
		}
		return array(
			'type' => 'json',
			'content' => $success
		);
	}

	public static function getMemoryListProducts(){
		if (null == self::$memoryListProducts && Config::get('USE_MEMORY_LIST') && isset($_COOKIE[MEMORY_LIST_NAME_KEY]) && ($memoryListId = $_COOKIE[MEMORY_LIST_NAME_KEY])) {
			self::$memoryListProducts = Db_Products_MemoryListProducts::getAllProductsByMemoryIdentifier($memoryListId);
		}
	}

	public static function countMemoryListProducts(){
		self::getMemoryListProducts();
		return self::$memoryListProducts ? count(self::$memoryListProducts) : 0;
	}

	public static function showPersistentMemoryListBox(){
		self::getMemoryListProducts();
		if (conf('USE_MEMORY_LIST')) {
			$shoppingCart = self::$S->Get('cart');
			self::$TPL->assign('shoppingCart', $shoppingCart);
			self::$TPL->assign('memoryListProducts', self::$memoryListProducts);
			self::$TPL->display('persistent_memory_list');
		}
	}

	public function saveProductAndThemeIdAction() {
		//set product theme to session
		self::$S->Set('sessionProductTheme', array(Utils::memoryProductIdEncode(post('productId', 'int')) => post('themeId', 'int')));
		return array(
			'type' => 'encoded_json',
			'content' => true
		);
	}

	public function ajaxGetByProductIdThemeIdAction() {
		$productId = post('productId', 'str');
		$sessionProductTheme = self::$S->Get('sessionProductTheme');

		$themeId = (isset($sessionProductTheme[$productId]) ? $sessionProductTheme[$productId] : Db_Products_Products::getProductThemeIsDefault(Utils::memoryProductIdDecode($productId)));

		return array(
			'type' => 'json',
			'content' => $themeId
		);
	}

	public function ajaxSendMemoryListToEmailAction() {
		$email = post('email' , 'string');
		$memoryListId = post('memoryListId' , 'string');
		if (!$email || !$memoryListId) {
			return false;
		}
		Utils::instantiateMail();
		self::$MAIL->Subject = t(T_PROJECT_TITLE, self::$PROJECT["pr_name"]);
		self::$MAIL->Body = self::$PROJECT["pr_domain_".conf('ENVIRONMENT')] . conf('MEMORY_LIST_PAGE_URL') . "?mlid=" . $memoryListId;
		self::$MAIL->AddAddress($email);
		$response = Utils::$MAIL->Send();
		if ($response == 'true') {
			return array(
				'type' => 'json',
				'content' => true
			);
		} else {
			return array(
				'type' => 'json',
				'content' => false
			);
		}
	}



}